/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package unb.wikinarua.geopartitura.view;

import java.util.ArrayList;

import unb.wikinarua.geopartitura.Main;
import unb.wikinarua.geopartitura.draw.Line;
import unb.wikinarua.geopartitura.util.Constants;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Join;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class DrawView extends View {
	
	public static float STROKE_WIDTH = 3f;
	public static int FRAMECOUNT = 0;

	private Main mainContext;
	
	// Paint
	private Paint paint = new Paint();
	private ArrayList<Line> lines;
	private int[] colors = {Color.BLUE, Color.RED, Color.GREEN, Color.MAGENTA, Color.CYAN, Color.YELLOW};
	private float probability=0;
	private int countDown = 10;
	private float messageCircleProportion = 0.025f;
	Paint tempPaint = new Paint();
	
	public DrawView(Context context) {
		super(context);
		
		mainContext = (Main) context;
		
		paint.setColor(Color.WHITE);
		paint.setStrokeWidth(STROKE_WIDTH);
		paint.setStrokeJoin(Join.ROUND);
		tempPaint.setColor(Color.BLACK);
		
		lines = new ArrayList<Line>();
		//Normalized lines
//		lines.add(new Line(0.1f, 0.5f, paint, colors[lines.size()], mainContext, lines.size()));
//		lines.add(new Line(0.35f, 0.20f, paint, colors[lines.size()], mainContext, lines.size()));
//		lines.add(new Line(-0.3f, -0.50f, paint, colors[lines.size()], mainContext, lines.size()));
		
		//Unormalized lines
//		lines.add(new Line(-85f, -80f, paint, colors[lines.size()], mainContext, lines.size()));
//		lines.add(new Line(-50f, 150f, paint, colors[lines.size()], mainContext, lines.size()));
//		lines.add(new Line(75f, 83f, paint, colors[lines.size()], mainContext, lines.size()));
//		lines.add(new Line(-100f, 50f, paint, colors[lines.size()], mainContext, lines.size()));
//		lines.add(new Line(-280.125f, -104.890f, paint, colors[lines.size()], mainContext, lines.size()));
//		lines.add(new Line(-80f, -70f, paint, colors[lines.size()], mainContext, lines.size()));
//		lines.add(new Line(45f, -98f, paint, colors[lines.size()], mainContext, lines.size()));
		randomizeStrings(10);
	}
	
	@Override
	public void onDraw(Canvas canvas) {
		
		//tempPaint = new Paint(Color.BLACK);
		
		
		FRAMECOUNT++;
		for (Line line : lines) {
			line.setCanvas(canvas);
			line.draw();
			if (Math.random()>1-line.getProbability()) {
				sendXMPPMessage(line.getLineID());
				tempPaint.setColor(line.getColor());
				//Desenha depois do lado direito do circulo
				canvas.drawText(line.getLineID() + " - " + line.getProbability(), canvas.getWidth()*0.05f+canvas.getHeight()*messageCircleProportion, canvas.getWidth()*0.05f, tempPaint);
			}
		}
		
		
		//Desenha um circulo com a cor do ponto da ultima mensagem enviada
		// Só pra visualizar a comunicação na tela
		canvas.drawCircle(canvas.getWidth()*0.05f, canvas.getHeight()*0.05f, canvas.getHeight()*messageCircleProportion, tempPaint);
		
		
//		paint.setColor(Color.WHITE);
//		canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, 12, paint);
		
		//Simulando as mensagens chegando.. como não tem ID ainda, tou usando o index do array
		if (Math.random()>0.9) {
			int simulatedIndex = (int) (Math.random()*lines.size());
			Line lineTemp = lines.get(simulatedIndex);
			lineTemp.setVibrate(true);
			lineTemp.setDecayStatus(true);
		}
		
	}

	private void sendXMPPMessage(String lineID) {
		// TODO Auto-generated method stub
		//Envia a mensagem XMPP pra corda com o ID x
		System.out.println("Envia a mensagem pro celular com ID = lineID");
	}
	
	public void simulateReceiveXMPPMessage(int lineID) {
		Line line = lines.get(lineID);
		line.setVibrate(true);
		line.setDecayStatus(true);
	}
	
	public void receiveXMPPMessage(String lineID) {
		for (Line line : lines) {
			if (line.getLineID().equalsIgnoreCase(lineID)) {
				line.setVibrate(true);
				line.setDecayStatus(true);
			}
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if ( (event.getAction() == MotionEvent.ACTION_DOWN) || 
				(event.getAction() == MotionEvent.ACTION_MOVE) ){
		
			float x = (event.getX() - (getWidth() / 2));
			float y = (event.getY() - (getHeight() / 2));
			
			if ((Math.abs(x) < 30) && (Math.abs(y) < 30)) {
				for (Line line : lines) {
					line.setVibrate(true);
					line.setDecayStatus(false);
				}
			} else {
				for (Line line : lines) {
					if (Constants.DBG) Log.i(Constants.TAG, "Ex: " + x + " Ey: " + y + " Lx:" + line.getX() + " Ly: " + line.getY());
					if ((line.getX() - x > -30) && (line.getX() - x < 30)
							&& (line.getY() - y > -30) && (line.getY() - y < 30)){
						line.setVibrate(true);
						line.setDecayStatus(false);
					} else {
						line.setDecayStatus(true);
					}
				}
			}
		} else if (event.getAction() == MotionEvent.ACTION_UP) {
//			float x = (event.getX() - (getWidth() / 2));
//			float y = (event.getY() - (getHeight() / 2));
			
//			if ((Math.abs(x) < 30) && (Math.abs(y) < 30)) {
//				for (Line line : lines) {
//					line.setVibrate(true);
//					line.setDecayStatus(true);
//				}
//			} else {
				for (Line line : lines) {
//					if (Constants.DBG) Log.i(Constants.TAG, "Ex: " + x + " Ey: " + y + " Lx:" + line.getX() + " Ly: " + line.getY());
//					if ((line.getX() - x > -30) && (line.getX() - x < 30)
//							&& (line.getY() - y > -30) && (line.getY() - y < 30)){
//						line.setVibrate(true);
						line.setDecayStatus(true);
//					}
//				}
			}
		}
//		return super.onTouchEvent(event);
		return true;
	}
	
	public void clearLines() {
		lines.clear();
//		lines = new ArrayList<Line>();
	}
	
	public void addLine(float lat, float lng) {
		lines.add(new Line(lat, lng, paint, colors[lines.size()], mainContext, lines.size()));
	}
	
	public void addLine(float lat, float lng, int colorIndex) {
		lines.add(new Line(lat, lng, paint, colors[colorIndex], mainContext, lines.size()));
	}
	
	public void addLine(float lat, float lng, int colorIndex, boolean updated) {
		lines.add(new Line(lat, lng, paint, colors[colorIndex], mainContext, lines.size(), updated));
	}
	
	public void randomizeStrings(int n) {
		float randX, randY;
		int randColor;
		
		for (int i=0 ; i < n; i++) {
			if (Math.random() > 0.5)
				randX = (float) Math.random();
			else
				randX = (float) Math.random() * -1;
			
			if (Math.random() > 0.5)
				randY = (float) Math.random();
			else
				randY = (float) Math.random() * -1;
			
			randColor = (int) (Math.random() * colors.length);
			if (Constants.DBG) Log.i(Constants.TAG, randX + " " + randY + " " + randColor);
			
			addLine(randX, randY, randColor);
			//lines.add(new Line(randX, randY, paint, colors[n], mainContext, lines.size()));
		}
	}

	public void setTime(int value) {
		FRAMECOUNT = value;
	}
	
	public int getColorLength() {
		return colors.length;
	}
	
}
